{% extends "base.html" %}

{% block content %}
<div class="container mt-4">
    <h2 class="mb-4">添加新设备</h2>

    <form method="POST" class="needs-validation" novalidate>
        <!-- 基础信息卡片 -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5>设备基本信息</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="name" class="form-label">设备名称</label>
                        <input type="text" class="form-control" id="name" name="name" required>
                        <div class="invalid-feedback">
                            请输入设备名称
                        </div>
                    </div>

                    <div class="col-md-6 mb-3">
                        <label for="ip" class="form-label">IP地址</label>
                        <input type="text" class="form-control" id="ip" name="ip" required
                            pattern="^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$">
                        <div class="invalid-feedback">
                            请输入有效的IPv4地址（如：192.168.1.1）
                        </div>
                    </div>

                    <div class="col-md-6 mb-3">
                        <label for="name" class="form-label">用户名（控制器可选）</label>
                        <input type="text" class="form-control" id="username" name="username" required>
                        <div class="invalid-feedback">
                            请输入用户名
                        </div>
                    </div>

                    <div class="col-md-6 mb-3">
                        <label for="name" class="form-label">密码（控制器可选）</label>
                        <input type="text" class="form-control" id="passwd" name="passwd" required>
                        <div class="invalid-feedback">
                            请输入密码
                        </div>
                    </div>

                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="device_type" class="form-label">设备类型</label>
                        <select class="form-select" id="device_type" name="device_type" required>
                            <option value="" disabled selected>请选择设备类型</option>
                            <option value="switch">交换机</option>
                            <option value="router">路由器</option>
                            <option value="firewall">防火墙</option>
                            <option value="controller">控制器</option>
                        </select>
                    </div>

                    <div class="col-md-6 mb-3">
                        <label for="group_id" class="form-label">设备分组</label>
                        <select class="form-select" id="group_id" name="group_id">
                            <option value="">未分组</option>
                            {% for group in groups %}
                            <option value="{{ group.id }}">{{ group.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <!-- SNMP配置卡片 -->
        <div class="card mb-4">
            <div class="card-header bg-info text-white">
                <h5>SNMP监控配置</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label for="snmp_community" class="form-label">SNMP团体名</label>
                        <input type="password" class="form-control" id="snmp_community" name="snmp_community"
                            value="public" required>
                        <small class="text-muted">默认值：public（建议修改为私有团体名）</small>
                    </div>

                    <div class="col-md-6 mb-3 d-flex align-items-end">
                        <button type="button" class="btn btn-outline-primary" onclick="testSNMPConnection()">
                            <i class="bi bi-plug"></i> 测试SNMP连接
                        </button>
                    </div>
                </div>

                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="enable_monitoring" name="enable_monitoring"
                        checked>
                    <label class="form-check-label" for="enable_monitoring">启用设备监控</label>
                </div>
            </div>
        </div>

        <!-- 流表配置卡片 -->
        <div class="card mb-4">
            <div class="card-header bg-warning text-dark">
                <h5>流表自动下发</h5>
            </div>
            <div class="card-body">
                <div class="alert alert-info">
                    <i class="bi bi-info-circle"></i> 将自动下发基础流表规则，将目标地址为本设备的数据包转发给控制器
                </div>

                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="enable_flow" name="enable_flow" checked>
                    <label class="form-check-label" for="enable_flow">启用流表自动下发</label>
                </div>
            </div>
        </div>

        <!-- 表单提交按钮 -->
        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
            <button type="submit" class="btn btn-primary me-md-2">
                <i class="bi bi-save"></i> 保存设备
            </button>
            <a href="{{ url_for('index') }}" class="btn btn-secondary">
                <i class="bi bi-x-circle"></i> 取消
            </a>
        </div>
    </form>
</div>

<!-- SNMP测试脚本 -->
<script>
    function testSNMPConnection() {
        const ip = document.getElementById('ip').value;
        const community = document.getElementById('snmp_community').value;

        if (!ip || !community) {
            alert('请先填写IP地址和SNMP团体名');
            return;
        }

        // 显示加载状态
        const btn = document.querySelector('button[onclick="testSNMPConnection()"]');
        const originalHtml = btn.innerHTML;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> 测试中...';
        btn.disabled = true;

        fetch('/test_snmp', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                ip: ip,
                community: community
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(`✅ SNMP连接成功\n\n设备名称: ${data.device_name || '未知'}\n系统描述: ${data.sys_desc || '未获取'}\nCPU负载: ${data.cpu_usage || 'N/A'}%`);
                } else {
                    alert('❌ SNMP连接失败: ' + (data.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('⚠️ 测试请求失败: ' + error.message);
            })
            .finally(() => {
                btn.innerHTML = originalHtml;
                btn.disabled = false;
            });
    }
</script>

<!-- 表单验证脚本 -->
<script>
    // 增强的IP地址验证
    document.getElementById('ip').addEventListener('input', function (e) {
        const ipPattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
        this.setCustomValidity(ipPattern.test(this.value) ? '' : '请输入有效的IPv4地址');
    });

    // Bootstrap表单验证
    (function () {
        'use strict'
        const form = document.querySelector('.needs-validation')
        form.addEventListener('submit', function (event) {
            if (!form.checkValidity()) {
                event.preventDefault()
                event.stopPropagation()
            }
            form.classList.add('was-validated')
        }, false)
    })()
</script>

<style>
    /* 自定义样式 */
    .card {
        border-radius: 0.5rem;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }

    .card-header {
        border-radius: 0.5rem 0.5rem 0 0 !important;
    }

    .invalid-feedback {
        display: none;
        width: 100%;
        margin-top: 0.25rem;
        font-size: 0.875em;
        color: #dc3545;
    }

    .was-validated .form-control:invalid~.invalid-feedback,
    .was-validated .form-control:invalid~.invalid-tooltip {
        display: block;
    }
</style>
{% endblock %}